package service

import (
	"bluebell-backend/common"
	"bluebell-backend/dao/mysql"
	"bluebell-backend/model/po"
	jwt "bluebell-backend/util"
	"crypto/md5"
	"encoding/hex"
	"errors"
	idworker "github.com/gitstliu/go-id-worker"
)

const secret = "xxxx.xxxx"

var idGen *idworker.IdWorker

func init() {
	idGen = &idworker.IdWorker{}
	idGen.InitIdWorker(1, 1)
}
func Register(email, password string) (int, error) {
	// 判断用户是否重复
	isRepeat := mysql.CheckIsRepeat(email)
	if isRepeat {
		return common.ERROR, errors.New("用户已存在")
	}

	//生成uuid
	UUID, err := idGen.NextId()
	if err != nil {
		return common.ERROR, err
	}

	// 密码加密
	password = encryptPassword(password)
	//实例化user对象
	user := &po.User{
		UUID:     UUID,
		Email:    email,
		Password: password,
	}
	return mysql.Insert(user), nil
}

func Login(email, password string) (int, string, error) {

	user, err := mysql.GetOneUserByEmail(email)
	if err != nil {
		return common.ERROR, "", err
	}
	// 说明用户存在

	// 比较密码
	if encryptPassword(password) != user.Password {
		// 密码错误
		return common.ERROR, "", errors.New("用户名或密码错误")
	}
	// 密码正确，生成token
	token, err := jwt.GenToken(user.UUID, user.Email)
	if err != nil {
		return common.ERROR, "", err
	}
	return common.SUCCESS, token, nil
}

func GetUserInfo(uuid int64) (int, error, *po.User) {

	//
	user, err := mysql.GetOneByUUID(uuid)
	if err != nil {
		return common.ERROR, err, nil
	}
	return common.SUCCESS, nil, user

}

func UpdateUserInfo(user *po.User, uuid int64) (int, error) {
	// 根据uuid更新信息
	return mysql.UpdateByUUID(user, uuid)

}

// encryptPassword 密码加密
func encryptPassword(oPassword string) string {
	h := md5.New()
	h.Write([]byte(secret))
	return hex.EncodeToString(h.Sum([]byte(oPassword)))
}
